package com.hyhy.hycloud.uaa.controller;

import com.hyhy.hycloud.commons.exception.HyCloudRuntimeException;
import com.hyhy.hycloud.uaa.UaaErrorType;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * /error错误处理
 *
 * @author Xuegui Yuan
 * @date 2018-09-25
 */
@RestController
public class ErrorController extends BasicErrorController {
    private ErrorAttributes errorAttributes;

    public ErrorController() {
        this(new DefaultErrorAttributes(), new ErrorProperties());
    }

    public ErrorController(ErrorAttributes errorAttributes,
                           ErrorProperties errorProperties) {
        super(errorAttributes, errorProperties);
        this.errorAttributes = errorAttributes;
    }

    private static final String PATH = "/error";

    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.ALL));
        Map<String, Object> result = new LinkedHashMap<>();
        Throwable throwable = errorAttributes.getError(new ServletWebRequest(request));
        if (throwable instanceof HyCloudRuntimeException) {
            result.put("status", ((HyCloudRuntimeException) throwable).getErrorCode());
            result.put("message", throwable.getMessage());
        } else {
            result.put("status", UaaErrorType.UNAUTHORIZED_ERROR.getErrorCode());
            result.put("message", UaaErrorType.UNAUTHORIZED_ERROR.getMessage());
        }
        result.put("data", body);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}
